#pragma once
#include <iostream>
#include <vector>
#include "InetAddr.hpp"
#include "Log.hpp"
#include "Mutex.hpp"

using namespace LogModule;
using namespace MutexModule;

class Route
{
    private:
        bool IsExists(InetAddr &peer)
        {
            for(auto &user:_online_user)
            {
                if(user==peer)
                {
                    return true;
                }
                return false;
            }
        }
        void AddUser(InetAddr &peer)
        {
            LOG(LogLevel::INFO)<<"新增了一个在线用户"<<peer.StringAddr();
            _online_user.push_back(peer);
        }
        void DeleteUser(InetAddr &peer)
        {
            for(auto iter=_online_user.begin();iter!=_online_user.end();iter++)
            {
                if(*iter==peer)
                {
                    LOG(LogLevel::INFO)<<"删除一个在线用户:"<<peer.StringAddr()<<"成功";
                    _online_user.erase(iter);
                    break;
                }
            }
        }
    public:
        Route()
        {}
        void MessageRoute(int sockfd,const std::string &message,InetAddr &peer)
        {
            LockGuard lockguard(_mutex);
            if(IsExists(peer))
            {
                AddUser(peer);
            }
            if(message=="QUIT")
            {
                DeleteUser(peer);
            }
            std::string send_message=peer.StringAddr()+"# "+message;
            for(auto &user:_online_user)
            {
                sendto(sockfd,message.c_str(),message.size(),0,(const struct sockaddr*)&(user.NetAddr()),sizeof(user.NetAddr()));
            }
        }
        ~Route()
        {}
    private:
        std::vector<InetAddr> _online_user;//在线用户
        Mutex _mutex;
};